package cn.ch.train.common.handler;

import cn.ch.train.common.exception.BusinessException;
import cn.ch.train.common.response.CommonResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 统一异常处理、数据预处理
 */
@ControllerAdvice
public class ControllerExceptionHandler {
    private static final Logger logger = LoggerFactory.getLogger(ControllerExceptionHandler.class);

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public CommonResponse exceptionHandler(Exception e) {
        CommonResponse commonResponse = new CommonResponse();
        logger.error("系统异常", e);
        commonResponse.setSuccess(false);
        commonResponse.setMessage("系统出现异常，请联系管理员");
        return commonResponse;
    }

    @ExceptionHandler(value = BusinessException.class)
    @ResponseBody
    public CommonResponse businessExceptionHandler(BusinessException e) {
        CommonResponse commonResponse = new CommonResponse();
        logger.error("业务异常：{}", e.getMessage());
        commonResponse.setSuccess(false);
        commonResponse.setMessage(e.getMessage());
        return commonResponse;
    }

    @ExceptionHandler(value = BindException.class)
    @ResponseBody
    public CommonResponse bindExceptionHandler(BindException e) {
        CommonResponse commonResponse = new CommonResponse();
        logger.error("校验异常：{}", e.getBindingResult().getAllErrors().get(0).getDefaultMessage());
        commonResponse.setSuccess(false);
        commonResponse.setMessage(e.getBindingResult().getAllErrors().get(0).getDefaultMessage());
        return commonResponse;
    }
}
